package com.aizhixin.lab.project.course.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.aizhixin.lab.account.dto.AccountDTO;
import cn.hutool.core.util.ZipUtil;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.company.domain.AccountDomain;
import com.aizhixin.lab.config.Config;
import com.aizhixin.lab.jsrun.domian.CodeDomain;
import com.aizhixin.lab.jsrun.service.JsRunService;
import com.aizhixin.lab.project.course.core.TaskStatus;
import com.aizhixin.lab.project.course.domain.*;
import com.aizhixin.lab.project.course.entity.*;
import com.aizhixin.lab.project.course.repository.*;
import com.aizhixin.lab.project.course.uilt.FileType;
import com.aizhixin.lab.project.course.uilt.NumToChinese;
import com.aizhixin.lab.project.course.vo.StuTaskNumVo;
import com.aizhixin.lab.project.course.vo.StuTaskScheduleVo;
import com.aizhixin.lab.project.course.vo.TaskScheduleManagementVo;
import com.aizhixin.lab.project.template.entity.ModuleTask;
import com.aizhixin.lab.project.template.entity.Project;
import com.aizhixin.lab.statistics.util.ReportUtils;
import com.aizhixin.lab.task.entity.Task;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

import static com.aizhixin.lab.project.course.uilt.FileType.getFileByFile;
import static com.aizhixin.lab.project.course.uilt.FileType.getImageFileType;

@Slf4j
@Service
@Transactional
public class ProjectGroupTaskService {
    @Autowired
    private ProjectGroupTaskRepository taskRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private ProjectClassStuRepository stuRepository;
    @Autowired
    private ProjectStuKnowledgeScoreRepository projectStuKnowledgeScoreRepository;
    @Autowired
    private ProjectStuSkillScoreRepository projectStuSkillScoreRepository;
    @Autowired
    private TeacherProjectPostRepository projectPostRepository;
    @Autowired
    private TeacherProjectSkillRepository projectSkillRepository;
    @Autowired
    private TeacherKnowledgePointRepository knowledgePointRepository;
    @Autowired
    private Config config;
    @Autowired
    private JsRunService jsRunService;
    @Autowired
    private TeacherModuleTaskRepository moduleTaskRepository;
    @Autowired
    private TeacherProjectModuleRepository moduleRepository;
    @Autowired
    private TeacherTaskWorkOrderRepository workOrderRepository;
    @Autowired
    private ProjectReleaseTaskFileRepository taskFileRepository;
    @Autowired
    private ExercisesStuAnswerRepository exercisesStuAnswerRepository;
    @Autowired
    private TeacherExercisesRepository exercisesRepository;
    public Map<String, Object> releaseTask(ReleaseTaskDomain domain) {
        Map<String, Object> result = new HashMap<>();
        Integer type;
        if (StringUtils.isEmpty(domain.getWorkOrderId())) {
            type = 2;
        } else {
            type = 1;
        }
        List<ProjectGroupTask> projectGroupTaskList = new ArrayList<>();
        for (String s : domain.getProjectClassId()) {
            if (!StringUtils.isEmpty(domain.getWorkOrderId())){
                Integer count = taskRepository.countByWorkOrderIdAndProjectClassId(domain.getWorkOrderId(), s);
                if (count>0){
                    result.put(ApiReturnConstants.ERROR, "班级已发布过此任务");
                    result.put(ApiReturnConstants.SUCCESS, false);
                    return result;
                }
            }else {
                Integer count = taskRepository.countByTaskIdAndAndProjectClassIdAndWorkOrderIdIsNull(domain.getTaskId(), s);
                if (count>0){
                    result.put(ApiReturnConstants.ERROR, "班级已发布过此任务");
                    result.put(ApiReturnConstants.SUCCESS, false);
                    return result;
                }
            }
            Integer count = stuRepository.countByProjectClassIdAndDeleteFlagAndGroupIdIsNull(s, DataValidity.VALID.getState());
            if (count>0){
                result.put(ApiReturnConstants.ERROR, "班级未分组!");
                result.put(ApiReturnConstants.SUCCESS, false);
                return result;
            }
            List<ProjectClassStu> stuList = stuRepository.findByProjectClassIdAndDeleteFlag(s, DataValidity.VALID.getState());
            for (ProjectClassStu projectClassStu : stuList) {
                ProjectGroupTask projectGroupTask = new ProjectGroupTask();
                projectGroupTask.setId(UUID.randomUUID().toString());
                projectGroupTask.setStuId(projectClassStu.getStuId());
                projectGroupTask.setTaskId(domain.getTaskId());
                if (!StringUtils.isEmpty(domain.getWorkOrderId())){
                    projectGroupTask.setWorkOrderId(domain.getWorkOrderId());
                }
                projectGroupTask.setProjectClassId(projectClassStu.getProjectClassId());
                projectGroupTask.setTaskStatus(TaskStatus.TASK_STATUS_INIT);
                projectGroupTask.setProjectId(projectClassStu.getProjectId());
                projectGroupTask.setPlanBeginDate(new Date());
                projectGroupTask.setPlanEndDate(domain.getTaskEndTime());
                projectGroupTask.setTaskType(type);
                projectGroupTask.setGroupId(projectClassStu.getGroupId());
                projectGroupTask.setDeleteFlag(0);
                projectGroupTask.setCreatedDate(new Date());
                projectGroupTaskList.add(projectGroupTask);
            }
        }
        taskRepository.save(projectGroupTaskList);
        result.put(ApiReturnConstants.DATA, "任务发布成功");
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }
    public String stuReleaseTask(StuReleaseTaskDomain domain){
        TeacherModuleTask moduleTask = new TeacherModuleTask();
        BeanUtils.copyProperties(domain, moduleTask);
        moduleTask.setId(UUID.randomUUID().toString());
        Integer num = moduleTaskRepository.countByModuleIdAndDeleteFlag(domain.getModuleId(), DataValidity.VALID.getState());
        moduleTask.setTaskNo(num);
        moduleTask.setModuleId(domain.getModuleId());
        moduleTask.setDeleteFlag(DataValidity.VALID.getState());
        moduleTask.setCreatedDate(new Date());
        moduleTask.setWorkOrderNum(0);
        moduleTaskRepository.save(moduleTask);
        TeacherProjectModule module = moduleRepository.findByIdAndDeleteFlag(domain.getModuleId(), DataValidity.VALID.getState());
        module.setTaskNum(moduleTaskRepository.countByModuleIdAndDeleteFlag(domain.getModuleId(),DataValidity.VALID.getState()));
        moduleRepository.save(module);
        ProjectClassStu projectClassStu = stuRepository.findOne(domain.getGroupMemberId());
        ProjectGroupTask projectGroupTask = new ProjectGroupTask();
        projectGroupTask.setId(UUID.randomUUID().toString());
        projectGroupTask.setStuId(projectClassStu.getStuId());
        projectGroupTask.setTaskId(moduleTask.getId());
        projectGroupTask.setProjectClassId(projectClassStu.getProjectClassId());
        projectGroupTask.setTaskStatus(TaskStatus.TASK_STATUS_INIT);
        projectGroupTask.setProjectId(projectClassStu.getProjectId());
        projectGroupTask.setRealityBeginDate(domain.getBeginTime());
        projectGroupTask.setPlanBeginDate(domain.getBeginTime());
        projectGroupTask.setTaskType(2);
        projectGroupTask.setDeleteFlag(0);
        projectGroupTask.setCreatedDate(new Date());
        projectGroupTask.setGroupId(projectClassStu.getGroupId());
        taskRepository.save(projectGroupTask);
        return "OK";
    }
    public void submitTask(SubmitTaskDomain domain) {
        ProjectGroupTask groupTask = taskRepository.findOne(domain.getTaskId());
        groupTask.setLanguage(domain.getLanguage());
        groupTask.setTaskStatus("pending");
        groupTask.setRealityEndDate(new Date());
        groupTask.setTaskNote(domain.getTask_note());
        groupTask.setTaskGain(domain.getTask_gain());
        groupTask.setFileName(domain.getFileName());
        groupTask.setTaskAccessory(domain.getFileUrl());

        Integer count = projectStuSkillScoreRepository.countByProjectId(domain.getProjectId());
        if (count == 0){
            List<TeacherProjectPost> projectPostList = projectPostRepository.findByProjectIdInAndDeleteFlag(domain.getProjectId(),0);
            List<String> postIds = projectPostList.stream().map(t -> t.getId()).collect(Collectors.toList());
            List<TeacherProjectSkill> projectSkillList = projectSkillRepository.findByPostIdInAndDeleteFlag(postIds,0);
            for (TeacherProjectSkill skoll:projectSkillList) {
                ProjectStuSkillScore stuSkillScore = new ProjectStuSkillScore();
                stuSkillScore.setId(UUID.randomUUID().toString());
                stuSkillScore.setSkillId(skoll.getId());
                stuSkillScore.setProjectId(domain.getProjectId());
                stuSkillScore.setScore(skoll.getGrade());
                projectStuSkillScoreRepository.save(stuSkillScore);
            }
        }
        List<TeacherKnowledgePoint> knowledgePointList = knowledgePointRepository.findByModuleTaskId(domain.getTaskId());
        for (TeacherKnowledgePoint data:knowledgePointList) {
            ProjectStuKnowledgeScore stuKnowledgeScore = new ProjectStuKnowledgeScore();
            stuKnowledgeScore.setId(UUID.randomUUID().toString());
            stuKnowledgeScore.setKnowledgeId(data.getId());
            stuKnowledgeScore.setProjectId(domain.getProjectId());
            stuKnowledgeScore.setScore(data.getGrade());
            projectStuKnowledgeScoreRepository.save(stuKnowledgeScore);
        }

        taskRepository.save(groupTask);
        taskFileRepository.deleteByProjectReleaseTaskId(groupTask.getId());
        List<ProjectReleaseTaskFile> taskFileList=new ArrayList<>();
        domain.getTaskFileDomainList().forEach(item->{
            ProjectReleaseTaskFile projectReleaseTaskFile = new ProjectReleaseTaskFile();
            BeanUtils.copyProperties(item,projectReleaseTaskFile);
            projectReleaseTaskFile.setProjectReleaseTaskId(groupTask.getId());
            taskFileList.add(projectReleaseTaskFile);
        });
        taskFileRepository.save(taskFileList);
//        auto(domain,groupTask);
        System.out.println("测评成功");
    }

    public void auto(SubmitTaskDomain domain,ProjectGroupTask groupTask){
        CodeDomain codeDomain = new CodeDomain();
        codeDomain.setLang(domain.getLanguage());
        if (!StringUtils.isEmpty(domain.getFileUrl())) {
            File file = new File(config.getBaseDir());
            HttpUtil.downloadFile(domain.getFileUrl(), file);
            String url = "";
            int i = domain.getFileUrl().lastIndexOf("/");

            File f = new File(config.getBaseDir() + "//" + domain.getFileUrl().substring(i + 1));
            String flieType = getFileByFile(f);
            Set<Map> set = new HashSet<>();
            if (flieType.equals("zip")) {
                Charset charset = Charset.forName("GBK");
                File outF = new File("/download");
                System.out.println(outF.getAbsolutePath());
                ZipUtil.unzip(f, outF, charset);
                if (f.exists()) {
                    String filetype1 = getImageFileType(f);
                    System.out.println(filetype1);
                    String filetype2 = getFileByFile(f);
                    codeDomain.setCode(filetype2);
                    System.out.println(filetype2);
                }
//            File[] files = outF.listFiles();
                List<File> fileList = new ArrayList<>();
                getAllFile(outF, fileList);
                for (File file2 : fileList) {
                    if (file2.isFile()) {//是否为文件
//                    int a = file2.getName().lastIndexOf("_");
//                    String newName = filepath + "\\" + file2.getName().substring(0, a);
                        System.out.println(file2.getName());
//                    file2.renameTo(new File(newName));//更改文件名称
                        String s = readFileByLines(file2.getAbsolutePath());
                        codeDomain.setCode(s);
                        Map map = jsRunService.codeRunDetection(codeDomain);
                        set.add(map);
                    }

                }

            }
            Boolean codeResult = true;
            String result = "";
            for (Map m : set) {
                Integer violationNum = (Integer) m.get("violationNum");
                if (violationNum == 1) {
                    codeResult = false;
                    break;
                } else {
                    String s = (String) m.get("verif");
                    if (!result.contains(s)) {
                        result += s + "  ";
                    }
                }
            }

            System.out.println(result);
            //查询是否需要代码自动评测
//        ResponseEntity<?> responseEntity = jsRunService.jsRun(codeDomain);
//        HttpStatus statusCode = responseEntity.getStatusCode();
//        System.out.println("dddddd");
            if (codeResult) {
                groupTask.setAutomaticGrade(getGrade(1));
                groupTask.setAutomaticCommit(result);
            } else {
                groupTask.setAutomaticGrade(getGrade(0));
                groupTask.setAutomaticCommit("代码出现错误请手动查看代码");
            }
        }
        taskRepository.save(groupTask);
    }
    private Integer getGrade(Integer type) {
        Random random = new Random();
        if (type == 0) {
            int i = random.nextInt(60);
            if (i < 40) {
                return getGrade(type);
            } else {
                return i;
            }
        } else {
            int i = random.nextInt(99);
            if (i < 80) {
                return getGrade(type);
            } else {
                return i;
            }
        }
    }


    private String readFileByLines(String fileName) {
        String s = "";
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
                s += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return s;
    }

    private void getAllFile(File file, List<File> fileList) {

        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                getAllFile(file1, fileList);
            } else {
                fileList.add(file1);
            }
        }


    }

    public void teacherCheckTask(TeacherCheckTaskDomain domain) {
        ProjectGroupTask groupTask = taskRepository.findByProjectIdAndStuIdAndDeleteFlagAndTaskId(domain.getProjectId(), domain.getStu_id(), 0, domain.getTaskId());
        groupTask.setTaskStatus("approved");
        groupTask.setTaskGrade(domain.getTaskGrade());
        groupTask.setTaskComment(domain.getTaskComment());
        groupTask.setCheckId(Long.parseLong(domain.getCheckId()));
        taskRepository.save(groupTask);
    }

    public StuTaskScheduleVo taskSchedule(TaskScheduleDomain domain) {
        String sql = "SELECT a.stu_id,b.name as stu_name,c.name as role_name FROM `c_project_class_stu` a left join t_user b on a.stu_id = b.id left join t_project_role c on a.role_id = c.`name` where a.project_id ='" + domain.getProjectId() + "'and a.stu_id ='" + domain.getStuId() + "'";
        List<StuTaskScheduleVo> info = pageJdbcUtil.getInfo(sql, taskScheduleRm);
        StuTaskScheduleVo scheduleVo = new StuTaskScheduleVo();
        for (StuTaskScheduleVo data : info) {
            int initCount = taskRepository.countByStuIdAndProjectIdAndDeleteFlagAndTaskStatus(data.getStuId(), domain.getProjectId(), 0, "init");
            int runningCount = taskRepository.countByStuIdAndProjectIdAndDeleteFlagAndTaskStatus(data.getStuId(), domain.getProjectId(), 0, "running");
            int approvedCount = taskRepository.countByStuIdAndProjectIdAndDeleteFlagAndTaskStatus(data.getStuId(), domain.getProjectId(), 0, "approved");
            int timeoutCount = taskRepository.countByStuIdAndProjectIdAndDeleteFlagAndTaskStatus(data.getStuId(), domain.getProjectId(), 0, "timeout");
            int countSum = taskRepository.countByProjectIdAndStuIdAndDeleteFlag(domain.getProjectId(), data.getStuId(), 0);
            data.setCompleted(approvedCount);
            data.setPostpone(timeoutCount);
            data.setUnderway(runningCount);
            data.setUnplayed(initCount);
            data.setTaskSum(countSum);
            if (approvedCount==0){
                data.setCompletedRatio(0);
            }else {
                data.setCompletedRatio(countSum / approvedCount);
            }
            if (timeoutCount==0){
                data.setPostponeRatio(0);
            }else {
                data.setPostponeRatio(countSum / timeoutCount);

            }

            BeanUtils.copyProperties(data, scheduleVo);
        }
        return scheduleVo;
    }
    RowMapper<TaskScheduleManagementVo> scheduleManagementRm = new RowMapper<TaskScheduleManagementVo>() {
        @Override
        public TaskScheduleManagementVo mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            TaskScheduleManagementVo domain = new TaskScheduleManagementVo();
            domain.setPlan_days(rs.getInt("plan_days"));
            domain.setPlan_begin_date(rs.getString("plan_begin_date"));
            domain.setPlan_end_date(rs.getString("plan_end_date"));
            domain.setReality_days(rs.getInt("reality_days"));
            domain.setReality_begin_date(rs.getString("reality_begin_date"));
            domain.setReality_end_date(rs.getString("reality_end_date"));
            domain.setTask_name(!StringUtils.isEmpty(rs.getString("task_name"))?rs.getString("task_name"):rs.getString("w_name"));
            domain.setStu_name(rs.getString("stu_name"));
            domain.setTask_status(rs.getString("task_status"));
            return domain;
        }
    };
    public <T> Map<String, Object> scheduleManagement(TaskSchedulePageDomain domain) {
        String sql = "SELECT a.plan_begin_date,a.plan_end_date,a.reality_begin_date,a.reality_end_date,b.name as stu_name,datediff(a.plan_end_date,a.plan_begin_date) as plan_days,datediff(a.reality_end_date,a.reality_begin_date) as reality_days,c.task_name,ct.w_name,a.task_status FROM `c_project_group_task` a left join t_user b on a.stu_id = b.id left join c_module_task c on a.task_id = c.id LEFT JOIN c_task_work_order ct ON a.task_id=ct.id where a.project_id ='" + domain.getProjectId() + "'and a.group_id ='" + domain.getGroupId() + "'";
        String countSql = "SELECT count(*) FROM `c_project_group_task` a left join t_user b on a.stu_id = b.id left join c_module_task c on a.task_id = c.id where a.project_id ='" + domain.getProjectId() + "'and a.group_id ='" + domain.getGroupId() + "'";
        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("a.created_date");
        dto.setAsc(false);
        sort.add(dto);
        return pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), scheduleManagementRm, sort, sql, countSql);
    }

    RowMapper<StuTaskScheduleVo> taskScheduleRm = new RowMapper<StuTaskScheduleVo>() {
        @Override
        public StuTaskScheduleVo mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            StuTaskScheduleVo domain = new StuTaskScheduleVo();
            domain.setStuId(rs.getLong("stu_id"));
            domain.setStuName(rs.getString("stu_name"));
            domain.setRoleName(rs.getString("role_name"));
            return domain;
        }
    };



    RowMapper<StuTaskListDomain> stuTaskRm = new RowMapper<StuTaskListDomain>() {

        @Override
        public StuTaskListDomain mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            StuTaskListDomain domain = new StuTaskListDomain();
            domain.setId(rs.getString("id"));
            domain.setTaskName(rs.getString("task_name"));
            domain.setStatus(rs.getString("task_status"));
            domain.setCommitTime(rs.getDate("reality_end_date"));
            domain.setGrade(rs.getInt("task_grade"));
            domain.setTaskId(rs.getString("task_id"));
            Integer a = rs.getInt("work_order_no");

//            rs.getInt("task_no");
            domain.setName("模块"+ NumToChinese.numToChinese(rs.getInt("module_no")+"")+"任务"+NumToChinese.numToChinese(rs.getInt("task_no")+""));
            if (a!=null&&a!=0){
                domain.setName(domain.getName()+"工单"+NumToChinese.numToChinese(a+""));
            }
            return domain;
        }
    };

    RowMapper<TaskGanttDiagramDomain> findProjectGanttChart = new RowMapper<TaskGanttDiagramDomain>() {

        @Override
        public TaskGanttDiagramDomain mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            TaskGanttDiagramDomain domain = new TaskGanttDiagramDomain();
            domain.setTaskName(rs.getString("task_name"));
            domain.setPlanBeginDate(rs.getString("plan_begin_date"));
            domain.setPlanEndDate(rs.getString("plan_end_date"));
            domain.setDays(rs.getString("days"));

            return domain;
        }
    };

    /**
     * 查看某个学生某个项目下的所有任务
     *
     * @param projectId
     * @param stuId
     * @return
     */
    public Map<String, Object> findMyTaskList(String projectId, Long stuId, String status) {
        Map<String, Object> result = new HashMap<>();
        String sql = "SELECT gt.id,mt.task_name,gt.task_status,gt.reality_end_date,gt.task_grade,mt.id task_id,ctwo.work_order_no,cp.module_no,mt.task_no FROM c_project_group_task gt LEFT JOIN c_module_task mt ON gt.task_id=mt.id LEFT JOIN c_project_module cp ON cp.id=mt.module_id LEFT JOIN c_task_work_order ctwo ON ctwo.id=gt.work_order_id WHERE gt.project_id='" + projectId + "' AND gt.stu_id=" + stuId;
        if (!StringUtils.isEmpty(status)) {
            sql += " and gt.task_status='" + status + "' ORDER BY gt.created_date ASC";
        }else {
            sql +=" ORDER BY gt.created_date ASC";
        }
        List<StuTaskListDomain> info = pageJdbcUtil.getInfo(sql, stuTaskRm);
        result.put(ApiReturnConstants.DATA, info);
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }

    /**
     * 查看学生某个任务成绩及点评
     *
     * @param id 学生任务ID
     * @return
     */
    public StuTaskInfoDomain findStuTaskInfo(String id,Long stuId) {
        ProjectGroupTask groupTask = taskRepository.findOne(id);

        StuTaskInfoDomain stuTaskInfoDomain = new StuTaskInfoDomain();
        if (groupTask!=null) {
            if (stuId.equals(groupTask.getStuId()) && groupTask.getRealityBeginDate() == null) {
                groupTask.setRealityBeginDate(new Date());
                taskRepository.save(groupTask);
            }
            BeanUtils.copyProperties(groupTask, stuTaskInfoDomain);
            stuTaskInfoDomain.setFileUrl(groupTask.getTaskAccessory());
            TeacherModuleTask moduleTask = moduleTaskRepository.findByIdAndDeleteFlag(groupTask.getTaskId(), DataValidity.VALID.getState());
            if (!Objects.isNull(moduleTask)){
                stuTaskInfoDomain.setTaskName(moduleTask.getTaskName());
            }
            if (!StringUtils.isEmpty(groupTask.getWorkOrderId())){
                TeacherTaskWorkOrder one = workOrderRepository.findOne(groupTask.getWorkOrderId());
                if (!Objects.isNull(one)){
                    stuTaskInfoDomain.setWorkOrderName(one.getWorkOrderName());
                }
            }
        }
        List<ProjectReleaseTaskFile> projectReleaseTaskFileList = taskFileRepository.findByProjectReleaseTaskId(id);
        List<ProjectReleaseTaskFileDomain> taskFileDomainList=new ArrayList<>();
        projectReleaseTaskFileList.forEach(item->{
            ProjectReleaseTaskFileDomain projectReleaseTaskFileDomain = new ProjectReleaseTaskFileDomain();
            BeanUtils.copyProperties(item,projectReleaseTaskFileDomain);
            taskFileDomainList.add(projectReleaseTaskFileDomain);
        });
        List<ExercisesStuAnswer> stuAnswerList = exercisesStuAnswerRepository.findByGroupTaskIdAndStuId(id,groupTask.getStuId());
        Integer byTaskId;
        if (StringUtils.isEmpty(groupTask.getWorkOrderId())){
            byTaskId = exercisesRepository.countByTaskId(groupTask.getTaskId());
        }else {
            byTaskId = exercisesRepository.countByTaskId(groupTask.getWorkOrderId());
        }
        Integer totalGrade=0;
        for (ExercisesStuAnswer exercisesStuAnswer : stuAnswerList) {
            totalGrade+=Integer.parseInt(exercisesStuAnswer.getComment());
        }
        if (byTaskId>0){
            stuTaskInfoDomain.setExercisesAutomaticGrade(totalGrade/byTaskId);
            stuTaskInfoDomain.setExercisesAutomaticRank(ReportUtils.getLevel(stuTaskInfoDomain.getExercisesAutomaticGrade()));
        }else {
            stuTaskInfoDomain.setExercisesAutomaticGrade(0);
            stuTaskInfoDomain.setExercisesAutomaticRank("F");
        }
        stuTaskInfoDomain.setTaskFileDomainList(taskFileDomainList);
        return stuTaskInfoDomain;
    }

    public TaskDegreeOfCompletionDomain getTaskDegreeOfCompletionDomain(String projectId, Long stuId) {
        TaskDegreeOfCompletionDomain taskDegreeOfCompletionDomain = new TaskDegreeOfCompletionDomain();
        Integer integer = taskRepository.countByProjectIdAndStuIdAndDeleteFlag(projectId, stuId, DataValidity.VALID.getState());
        List<String> statusList = new ArrayList<>();
        statusList.add(TaskStatus.TASK_STATUS_PENDING);
        statusList.add(TaskStatus.TASK_STATUS_APPROVED);
        Integer integer1 = taskRepository.countByProjectIdAndStuIdAndTaskStatusInAndDeleteFlag(projectId, stuId, statusList, DataValidity.VALID.getState());
        taskDegreeOfCompletionDomain.setTotalNum(integer);
        taskDegreeOfCompletionDomain.setFinishNum(integer1);
        return taskDegreeOfCompletionDomain;
    }

    public void TaskStatusUpdateJob() {
        List<String> list = new ArrayList<>();
        list.add("init");
        list.add("running");
        List<ProjectGroupTask> groupTaskList = taskRepository.findByTaskStatusInAndDeleteFlag(list, 0);
        Map map = groupTaskList.stream().collect(Collectors.groupingBy(ProjectGroupTask::getTaskStatus));
        List<ProjectGroupTask> taskInitList = (List<ProjectGroupTask>) map.get("init");
        List<ProjectGroupTask> taskRunningList = (List<ProjectGroupTask>) map.get("running");
        if (taskInitList != null) {
            for (ProjectGroupTask task : taskInitList) {
                if (task.getPlanBeginDate() == DateUtil.parse(DateUtil.today(), "yyyy-MM-dd")) {
                    task.setTaskStatus("running");
                    taskRepository.save(task);
                }
            }
            if (taskRunningList != null) {
                for (ProjectGroupTask task : taskRunningList) {
                    if (task.getPlanEndDate() == DateUtil.parse(DateUtil.today(), "yyyy-MM-dd")) {
                        task.setTaskStatus("timeout");
                        taskRepository.save(task);
                    }
                }
            }
        }
    }

//    public StuTaskNumVo findStuTaskInfo(String taskId){
//        StuTaskNumVo stuTaskInfoVo = new StuTaskNumVo();
//        ProjectGroupTask projectGroupTask = taskRepository.findOne(taskId);
//        BeanUtils.copyProperties(stuTaskInfoVo,projectGroupTask);
//
//
//        return stuTaskInfoVo;
//    }

    /**
     * 批阅学生任务
     *
     * @param domain
     * @param dto
     * @return
     */
    public Map<String, Object> approvalStuTask(StuTaskDomain domain, AccountDTO dto) {
        Map<String, Object> map = new HashMap<>();
        ProjectGroupTask projectGroupTask = taskRepository.findOne(domain.getId());
        if (Objects.isNull(projectGroupTask)) {
            map.put(ApiReturnConstants.SUCCESS, false);
            map.put(ApiReturnConstants.MESSAGE, "未找到任务");
            return map;
        }
        projectGroupTask.setTaskStatus(TaskStatus.TASK_STATUS_APPROVED);
        projectGroupTask.setTaskGrade(domain.getTaskGrade());
        projectGroupTask.setTaskComment(domain.getTaskComment());
        projectGroupTask.setCheckId(dto.getId());
        taskRepository.save(projectGroupTask);
        map.put(ApiReturnConstants.SUCCESS, true);
        map.put(ApiReturnConstants.DATA, "批阅成功");
        return map;
    }

    /**
     * 获取学生任务提交数和总数
     *
     * @param projectId
     * @param stuId
     * @return
     */
    public StuTaskNumVo findStuTaskNum(String projectId, Long stuId) {
        List<String> list = new ArrayList<>();
        list.add(TaskStatus.TASK_STATUS_APPROVED);
        list.add(TaskStatus.TASK_STATUS_PENDING);
        Integer integer = taskRepository.countByProjectIdAndStuIdAndTaskStatusInAndDeleteFlag(projectId, stuId, list, DataValidity.VALID.getState());
        StuTaskNumVo stuTaskNumVo = new StuTaskNumVo();
        stuTaskNumVo.setCommitNum(integer);
        Integer integer1 = taskRepository.countByProjectIdAndStuIdAndDeleteFlag(projectId, stuId, DataValidity.VALID.getState());
        stuTaskNumVo.setTotalNum(integer1);
        return stuTaskNumVo;
    }


    /**
     * 查询项目进度甘特图
     *
     * @return
     */
    public List<TaskGanttDiagramDomain> findProjectGanttChart(String projectId) {
        String sql = "SELECT DISTINCT b.task_name,a.plan_begin_date,a.plan_end_date,TIMESTAMPDIFF(DAY,a.plan_begin_date,a.plan_end_date) as days FROM `c_project_group_task` a left  join c_module_task b on a.task_id = b.id WHERE a.project_id='"+projectId+"'";
        List<TaskGanttDiagramDomain> info = pageJdbcUtil.getInfo(sql, findProjectGanttChart);
        return info;
    }
}
